<!DOCTYPE html>
<html>
<head>
<script src="/js-test-resources/js-test.js"></script>
<script>
function loadScript(url, async, onload, onerror) {
    var script = document.createElement("script");
    script.async = async;
    script.onload = onload;
    if (onerror)
        script.onerror = onerror;
    script.src = url;
    document.head.appendChild(script);
}
</script>
</head>
<body>
<script>
description("Slow scripts that fail to load should not dispatch multiple error events");

window.jsTestIsAsync = true;

if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

var firstOnErrorHandlerCount = 0;
var secondOnErrorHandlerCount = 0;
function verifyAndFinish() {
    shouldBe("firstOnErrorHandlerCount", "1");
    shouldBe("secondOnErrorHandlerCount", "1");
    finishJSTest();
};

function failedFirst() {
    firstOnErrorHandlerCount++;
    // Issue another script load so as to have the script runner
    // revisit its script queue. This should not result in this
    // onerror handler running again.
    var continuation = secondOnErrorHandlerCount ? verifyAndFinish : undefined;
    loadScript("resources/success.js?1", true, continuation);
}

function failedSecond() {
    secondOnErrorHandlerCount++;
    var continuation = firstOnErrorHandlerCount ? verifyAndFinish : undefined;
    loadScript("resources/success.js?2", true, continuation);
}

function unexpectedLoad() {
    testFailed("Script should not have loaded");
    finishJSTest();
}

loadScript("resources/success.js?3", false);
loadScript("resources/slow-nonexisting-script.php?sleep=1", false, unexpectedLoad, failedFirst);
loadScript("resources/slow-nonexisting-script.php?sleep=2", false, unexpectedLoad, failedSecond);
</script>
</body>
</html>
